package com.example.demo.core.tree;

import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Data
public class TreeBuilder {
    public static <T extends TreeNode, S extends TreeNode> List<T> convert(
            List<S> sources,
            Long pid,
            TreeNodeAdapter<S, T> createNode) {
        List<T> tree = new ArrayList<>();

        for(int i=0;i<sources.size();i++) {
            S source = sources.get(i);

            T node = createNode.newNode(source);
            BeanUtils.copyProperties(source, node);

            Long cPid = source.getPid();
            if(Objects.equals(pid, cPid)) {
                node.setChildren(TreeBuilder.convert(sources, source.getId(), createNode));
                tree.add(node);
            }
        }
        return tree;
    }
}
